package com.lazyking.mynetty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

public class WebSocketIndexPageHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    private String websocketPath;
    public WebSocketIndexPageHandler(String websocketPath) {
        this.websocketPath = websocketPath;
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req){
        if(req.uri().equals("/")){
            ByteBuf content = Unpooled.copiedBuffer((
                    "<html><body>" +
                            "<script>" +
                            "var ws = new WebSocket('ws://' + location.host + '/" + websocketPath + "');" +
                            "ws.onmessage = function(e){console.log('Received: ' + e.data)};" +
                            "ws.onopen = function(){ws.send('Hello Server!');};" +
                            "</script>" +
                            "<h3>WebSocket Test Page</h3>" +
                            "</body></html>"
            ).getBytes());

            FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
            res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
            res.headers().setInt(CONTENT_LENGTH, content.readableBytes());
            ctx.writeAndFlush(res).addListener(ChannelFutureListener.CLOSE);
        }else {
            ctx.fireChannelRead(req.retain());
        }

    }
}
